package me.jzn.alib.utils;

import android.database.Cursor;

import java.util.Date;

public class CursorUtil {
    public static String getString(Cursor c, String colName) {
        return c.getString(c.getColumnIndexOrThrow(colName));
    }

    public static short getShort(Cursor c, String colName) {
        return c.getShort(c.getColumnIndexOrThrow(colName));
    }

    public static Short getShortObj(Cursor c, String colName) {
        String str = getString(c, colName);
        return str == null ? null : Short.valueOf(str);
    }

    public static int getInt(Cursor c, String colName) {
        return c.getInt(c.getColumnIndexOrThrow(colName));
    }

    public static Integer getIntObj(Cursor c, String colName) {
        String str = getString(c, colName);
        return str == null ? null : Integer.valueOf(str);
    }

    public static long getLong(Cursor c, String colName) {
        return c.getLong(c.getColumnIndexOrThrow(colName));
    }

    public static Long getLongObj(Cursor c, String colName) {
        String str = getString(c, colName);
        return str == null ? null : Long.valueOf(str);
    }

    /**
     * sqlite 自动把boolean存储为0/1
     */
    public static boolean getBoolean(Cursor c, String colName) {
        return 0 != getInt(c, colName);
    }

    public static Boolean getBoolObj(Cursor c, String colName) {
        String str = getString(c, colName);
        return str == null ? null : Boolean.valueOf(str);
    }

    public static byte[] getBlob(Cursor c, String columnName) {
        return c.getBlob(c.getColumnIndex(columnName));
    }

    /**
     * sqlite 不支持date类型，存储的时候可以存储为unix时间戳，这样可以利用sqlite的时间函数转换成YYYY-MM-DD HH:MM:SS形式
     */
    public static Date getDate(Cursor c, String colName) {
        Long timestamp = getLong(c, colName);
        if (timestamp != null) {
            return new Date(timestamp * 1000);
        }
        return null;
    }
}
